<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>圆形的选择拖拽</title>
    <style>
        body{margin: 0;overflow: hidden}
        #canvas{background: antiquewhite;}
    </style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
    const canvas=document.getElementById('canvas');
    canvas.width=window.innerWidth;
    canvas.height=window.innerHeight;
    const  ctx=canvas.getContext('2d');

    //简单圆形
    class Ball{
        constructor(r=0,color='#000'){
            this.r=r;
            this.color=color;
            this.x=0;
            this.y=0;
        }
        draw(ctx){
            const {x,y,r,color}=this;
            ctx.save();
            ctx.beginPath();
            ctx.arc(x,y,r,0,Math.PI*2);
            ctx.fillStyle=color;
            ctx.fill();
            ctx.restore();
        }
    }

    const ball = new Ball(90);
    ball.x=200;
    ball.y=200;
    render();

    /*鼠标拖拽*/
    //鼠标位减图形位
    let subPos=null;
    //鼠标是否在图形中
    let drag=false;

    //点击事件
    canvas.addEventListener('mousedown',mousedownFn);
    //移动
    canvas.addEventListener('mousemove',mousemoveFn);
    //鼠标抬起
    canvas.addEventListener('mouseup',mouseupFn);

    function mousedownFn(event){
        //鼠标位置
        const mousePos=getMousePos(event);
        //鼠标位减图形位
        subPos={
            x:mousePos.x-ball.x,
            y:mousePos.y-ball.y,
        };
        //判断鼠标是否在图形中
        drag=containPoint(ball,mousePos);
    }
    function mousemoveFn(event){
        const mousePos=getMousePos(event);
        if(drag){
            ball.x=mousePos.x-subPos.x;
            ball.y=mousePos.y-subPos.y;
            render();
        }
    }
    function mouseupFn(){
        drag=false;
    }
    //判断点是否在图形中
    function containPoint(obj,mousePos){
        //获取鼠标到圆心的距离 len
        const len=Math.sqrt(subPos.x*subPos.x+subPos.y*subPos.y);
        //判断鼠标到圆心的距离是否小于r
        return len<obj.r;
    }

    //获取鼠标在canvas中的位置
    function getMousePos(event){
        //获取鼠标位置
        const {clientX,clientY}=event;
        //获取canvas 边界位置
        const {top,left}=canvas.getBoundingClientRect();
        //计算鼠标在canvas 中的位置
        const x=clientX-left;
        const y=clientY-top;
        return {x,y};
    }


    function render(){
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ball.draw(ctx);
    }

</script>
</body>
</html>
